package controllers;

import play.*;
import play.db.ebean.Transactional;
import play.mvc.*;
import views.html.*;
import models.*;
import static play.data.Form.*;
import play.data.Form;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.node.ObjectNode;

import play.libs.F;
import play.libs.F.Promise;
import play.libs.Json;
import play.libs.WS;

public class Application extends Controller {

    public static Result index() {
        return ok(index.render());
    }

    public static Result setRuLocale() {
        changeLang("ru");
        return ok(index.render());
    } 
    
    public static Result setEnLocale() {
        changeLang("en");
        return ok(index.render());
    } 
    

    @Transactional
    public static Promise<Result> handle() {
        Logger.info("'Handle' start");
        
        Promise<Player> promiseOfPlayer = Promise.promise(
            new F.Function0<Player>() {
                public Player apply() {
                    try
                    {
                    	Form<Player> player = form(Player.class).bindFromRequest();
                    	player.get().save();
                    	List<Player> players = Player.find.where().orderBy("playerId DESC").setMaxRows(1).findList();
                    	Logger.info("Player saved");
                    	return players.get(0);                    
                    }
                    catch(Exception e)
                    {
                        return null;
                    }

                }
            }
        );
        Logger.info("'Handle' end");
        return promiseOfPlayer.map(new F.Function<Player, Result>() {
            public Result apply(Player player) {
                if(player == null)
                    return ok(errorPage.render());
                Logger.info("Got player");
                return ok(handlePage.render(player.name, player.accuratePasses, player.goals));
            }
        });
    }
    
    public static Result getPlayersJson() throws JsonProcessingException {
        List<Player> players = Player.find.all();
        ObjectNode result = Json.newObject();
        result.put("queueElements", Json.toJson(players));
        return ok(result);
    }
    
    public static Promise<Result> getHelp() {
        return WS.url("http://rus.rfpl.org/").get().map(new F.Function<WS.Response, Result>() {
            public Result apply(WS.Response response) {
                return ok(response.getBody()).as("html");
            }
        });
    }


}
